package eai.tp2.core;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

/**
 * This class is responsible to load the xml files.
 */
public class CameraListReader {

	// fileName will contain the name of the file and therefore the brand
	private String[] brands = null;
	public Map<String, List<Element>> cameras = new HashMap<String, List<Element>>();
	
	public CameraListReader(String[] brands) throws JDOMException, IOException {
		this.brands = brands;
		// for all the brands create a list of different models
		for (int i = 0; brands.length > i; i++) {					
			readXML(brands[i]);
		}
	}
	// this method will read the XML file to a Document
	@SuppressWarnings("unchecked")
	private void readXML(String brand) throws JDOMException, IOException {


			SAXBuilder builder = new SAXBuilder(true);
			builder.setFeature("http://apache.org/xml/features/validation/schema", true);
			Document doc = builder.build(System.getProperty("user.dir")+File.separatorChar+"data"+File.separatorChar+ brand + ".xml");			
			XPath xpath = XPath.newInstance("/digital_camera_list/digital_camera");
			List<Element> list = xpath.selectNodes(doc);
			if(cameras.get(brand)!=null) {
				List<Element> temp = cameras.get(brand);
				temp.addAll(list);
			}
			else {
				cameras.put(brand, list);
			}

	}
}
